/*
 * @Title: community
 * @Description: TODO
 * @author MI
 * @date 2022/7/18 14:35
 * @version
 */
package com.shanshan.community.controller;

import com.google.code.kaptcha.Producer;
import com.shanshan.community.entity.User;
import com.shanshan.community.service.UserService;
import com.shanshan.community.util.CommunityConstant;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

/**
 * @author MI
 * @ClassName: LoginController
 * @Description: 登录相关的控制器
 * @date 2022/7/18 14:35
 */

@Controller
public class LoginController implements CommunityConstant {

    private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private Producer kaptchaProducer;

    @Autowired
    private UserService userService;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    /*访问注册页面*/
    @GetMapping("/register")
    public String getRegisterPage() {
        return "/site/register";
    }

    /*访问登录页面*/
    @GetMapping("/login")
    public String getLoginPage() {
        return "/site/login";
    }

    /*注册时的逻辑处理*/
    @PostMapping("/register")
    public String register(Model model, User user) {
        Map<String, Object> register = userService.register(user);
        if (register == null || register.isEmpty()) {
            model.addAttribute("msg", "注册成功，我们已经想你的邮箱发送了一封激活邮件，请尽快激活");
            model.addAttribute("target", "/index");
            return "/site/operate-result";
        } else {
            //注册失败的处理
            model.addAttribute("usernameMsg", register.get("usernameMsg"));
            model.addAttribute("passwordMsg", register.get("passwordMsg"));
            model.addAttribute("emailMsg", register.get("emailMsg"));
            return "/site/register";
        }
    }

    /*激活时的逻辑处理*/
    @GetMapping("/activation/{userId}/{code}")
    public String activation(Model model, @PathVariable("userId") int userId, @PathVariable("code") String code) {
        int result = userService.activation(userId, code);
        if (result == ACTIVATION_SUCCESS) {
            model.addAttribute("msg", "激活成功");
            model.addAttribute("target", "/login");
        } else if (result == ACTIVATION_REPEAT) {
            model.addAttribute("msg", "激活重复");
            model.addAttribute("target", "/index");
        } else {
            model.addAttribute("msg", "激活失败，激活码不正确");
            model.addAttribute("target", "/index");
        }
        return "/site/operate-result";
    }

    @GetMapping("/kaptcha")
    public void getKaptchar(HttpServletResponse response, HttpSession session) {
        //生产验证码
        String text = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(text);
        //存入session
        session.setAttribute("kaptcha", text);
        //传到浏览器
        response.setContentType("image/png");
        try {
            ServletOutputStream os = response.getOutputStream();
            ImageIO.write(image, "png", os);
        } catch (IOException e) {
            LOGGER.error("响应验证码失败" + e.getMessage());
        }

    }

    //login.html
    @PostMapping("/login")
    public String login(String username, String password, String code, boolean rememberMe, HttpServletResponse response, HttpSession session, Model model) {
        /* 检查验证码*/
        //从session中获取系统生成的验证码
        String kaptcha = (String) session.getAttribute("kaptcha");
        //系统生成的验证码不能为空，用户输入的验证码不能为空，两个验证码要相等
        if (StringUtils.isBlank(kaptcha) || StringUtils.isBlank(code) || !kaptcha.equalsIgnoreCase(code)) {
            //验证码验证失败
            model.addAttribute("codeMsg", "验证码错误");
            return "/site/login";
        }

        /*检查账号*/
        int expiredSeconds = rememberMe ? REMEMBER_EXPIRED_SECONDS : DEFAULT_EXPIRED_SECONDS;
        Map<String, Object> map = userService.login(username, password, expiredSeconds);
        if (map.containsKey("ticket")) {
            Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
            cookie.setMaxAge(expiredSeconds);
            cookie.setPath(contextPath);
            response.addCookie(cookie);
            //重定向
            return "redirect:/index";
        } else {
            //model.addAttribute如果值是空
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            return "/site/login";
        }
    }

    //登出
    @GetMapping("/logout")
    public String logout(@CookieValue String ticket) {
        userService.logout(ticket);
        return "redirect:/login";
    }
}

